package com.xxx.chat.server.handler;

import com.xxx.chat.message.LoginRequestMessage;
import com.xxx.chat.message.LoginResponseMessage;
import com.xxx.chat.server.service.UserServiceFactory;
import com.xxx.chat.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 登录请求处理handler
 * SimpleChannelInboundHandler<T>可以只监听感兴趣的类型的消息
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();    // 用户名
        String password = msg.getPassword();    // 密码

        // 登录操作，返回登录是否成功
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage message;
        if (login) {  // 登录成功
            // 将用户绑定到当前channel
            SessionFactory.getSession().bind(ctx.channel(), username);
            // 返回登录成功消息
            message = new LoginResponseMessage(true, "登录成功");
        } else {  // 登录失败
            // 返回登录失败消息
            message = new LoginResponseMessage(false, "用户名或密码不正确");
        }
        // 发送消息
        ctx.writeAndFlush(message);
    }
}
